<?php
class SettingService extends BaseDbService
{
	private static $data;
	public function __construct()
	{
		$this->dao	= new SettingDao();
	}
	
	public function get($skey,$cache=false)
	{
		if($cache)
		{
			if(empty(self::$data))
			{
				$cache 	= new LtCache();
				$cache->init();
				$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."setting");
				self::$data	= $ch->get('settings');
			}
			
			if(!empty($tmp) && !empty($tmp[$skey]))
			{
				return $tmp[$skey];
			}
		}
		
		$tmp = $this->dao->fetchRows(array());
		if(empty($tmp))
		{
			return false;
		}
		$val = array();
		foreach($tmp as $lv)
		{
			$val[$lv['skey']] = unserialize($lv['val']);
		}
		self::$data = $val;
		
		if($cache)
		{
			$this->updateCache();
		}
		
		return self::$data[$skey];
	}
	
	public function add($skey,$data,$cache=false)
	{
		$result	= parent::add(array('skey'=>$skey,'val'=>serialize($data)));
		if($cache)
		{
			$this->updateCache($skey);
		}
		return $result;
	}
	
	public function update($skey,$data,$replace=false,$cache=false)
	{
		if(!$replace)
		{
			$tmp	= $this->get($skey);
			foreach($tmp as $k=>$v)
			{
				if(!array_key_exists($k,$data))
				{
					$data[$k]		= $v;
				}
			}
		}
		
		$condition['expression'] 	= "skey = :skey";
		$condition['value']['skey'] = $skey;
		$result	= $this->dao->updateRows($condition, array('val'=>serialize($data)));
		if($cache)
		{
			$this->updateCache();
		}
		return $result;
	}
	
	private function updateCache()
	{
		$tmp = $this->dao->fetchRows(array());
		if(empty($tmp))
		{
			return false;
		}
		$val = array();
		foreach($tmp as $lv)
		{
			$val[$lv['skey']] = unserialize($lv['val']);
		}
		self::$data = $val;
		
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."setting");
		$skey 	= 'settings';
		$tmp	= $ch->get($skey);
		if($tmp!==false)
		{
			$ch->update($skey,$val);
		}
		else
		{
			$ch->add($skey,$val);
		}
		return true;
	}
}